package com.example.slidingexample;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;

import android.util.Log;

public class Utility {
	public static String getDataFromWebService(String strUrl,
			ArrayList<NameValuePair> nameValuePairs) {
		StringBuffer strBuffer = new StringBuffer();
		// String line = null;
		InputStream is = null;
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(strUrl);
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection" + e.toString());
		}

		try {
			int ch;
			while ((ch = is.read()) != -1)
				strBuffer.append((char) ch);

			is.close();
		} catch (IOException e) {
			// System.out.println("Error : " + e.toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// return line;
		return strBuffer.toString();
	}

	public static String getDataFromWebService(String strUrl) {
		StringBuffer strBuffer = new StringBuffer();
		// String line = null;
		InputStream is = null;
		try {
			System.out.println("getdata from web ser url:-> " + strUrl);
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(strUrl);
			// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();

			int in = response.getStatusLine().getStatusCode();
			System.out.println("Responce code :-> " + in);

		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection" + e.toString());
		}

		try {
			int ch;
			while ((ch = is.read()) != -1)
				strBuffer.append((char) ch);

			is.close();
		} catch (IOException e) { // System.out.println("Error : " +
									// e.toString());

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// return line;
		return strBuffer.toString();
	}

	public static String getData(String strUrl) throws ClientProtocolException,
			IOException {
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet(strUrl);
		HttpResponse response = client.execute(request);
		// Get the response
		BufferedReader rd = new BufferedReader(new InputStreamReader(response
				.getEntity().getContent()));
		String line = null;
		StringBuffer buffer = new StringBuffer();
		while ((line = rd.readLine()) != null) {
			 buffer.append(line);
		}
		return buffer.toString();
	}

	public static String trusted_certificate(String url) {
		HttpURLConnection con = null;
		StringBuffer strBuffer1 = new StringBuffer();
		InputStream is1 = null;
		try {

			System.out.println("trusted url  :->  " + url);
			URL murl = new URL(url);
			trustAllHosts();
			HttpsURLConnection https = (HttpsURLConnection) murl
					.openConnection();
			https.setHostnameVerifier(DO_NOT_VERIFY);
			con = https;
			con.setReadTimeout(100000);
			con.setConnectTimeout(150000);
			con.setRequestMethod("GET");
			con.setDoInput(true);
			con.connect();
			is1 = con.getInputStream();

			int in = https.getResponseCode();
			System.out.println("Resopnce code trusted certi:-> " + in);

		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			int ch;

			while ((ch = is1.read()) != -1) {
				strBuffer1.append((char) ch);
			}

			is1.close();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("trusted string buffer :->  "
				+ strBuffer1.toString());
		// return line;
		return strBuffer1.toString();
	}

	private static void trustAllHosts() {
		// Create a trust manager that does not validate certificate chains
		TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
			public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				return new java.security.cert.X509Certificate[] {};
			}

			public void checkClientTrusted(X509Certificate[] chain,
					String authType) throws CertificateException {
			}

			public void checkServerTrusted(X509Certificate[] chain,
					String authType) throws CertificateException {
			}
		} };

		// Install the all-trusting trust manager
		try {
			SSLContext sc = SSLContext.getInstance("TLS");
			sc.init(null, trustAllCerts, new java.security.SecureRandom());
			HttpsURLConnection
					.setDefaultSSLSocketFactory(sc.getSocketFactory());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	};

	// public static String trusted
	public static String trusted_certificate2(String url) {

		String result1 = new Utility().testIt(url);
		if (result1 != null) {
			System.out.println("result null in trust 2");
			return result1;
		} else {
			System.out.println("result in trust 2 :--" + result1);

			// url = "https://www.kaz.nl/app/?method=areacode%7capplist";
			HttpURLConnection con2 = null;

			StringBuffer strBuffer1 = new StringBuffer();
			InputStream is1 = null;

			int g = 0;

			try {

				System.out.println("trusted url22  :->  " + url);
				URL murl = new URL(url);
				trustAllHosts();
				HttpsURLConnection https = (HttpsURLConnection) murl
						.openConnection();
				https.setHostnameVerifier(DO_NOT_VERIFY);
				con2 = https;
				con2.setReadTimeout(10000);
				con2.setConnectTimeout(15000);
				con2.setRequestMethod("GET");
				con2.setDoInput(true);
				con2.connect();
				is1 = con2.getInputStream();

			} catch (Exception e) {
				e.printStackTrace();
			}

			try {
				System.out.println("red2:" + is1.available());
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			String result = convertStreamToString(is1);
			System.out.println("red result length  --:" + result.length()
					+ " : " + result);

			return result;
		}
	}

	private static String convertStreamToString(InputStream is) {
		/*
		 * To convert the InputStream to String we use the
		 * BufferedReader.readLine() method. We iterate until the BufferedReader
		 * return null which means there's no more data to read. Each line will
		 * appended to a StringBuilder and returned as String.
		 */
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println("redsb -: " + sb.length() + " : " + sb.toString());
		return sb.toString();
	}

	private String testIt(String https_url) {

		// String https_url = "https://www.google.com/";
		// https_url = "https://www.kaz.nl/app/?method=areacode%7capplist";
		String sb = null;
		URL url;
		try {

			url = new URL(https_url);
			HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

			// dumpl all cert info
			print_https_cert(con);
			int in = con.getResponseCode();
			System.out.println("Resopnce code trusted certi 22:-> " + in);
			// dump all the content
			sb = print_content(con);

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb;
	}

	private void print_https_cert(HttpsURLConnection con) {

		if (con != null) {

			try {

				System.out.println("Response Code : " + con.getResponseCode());
				System.out.println("Cipher Suite : " + con.getCipherSuite());
				System.out.println("\n");

				Certificate[] certs = con.getServerCertificates();
				for (Certificate cert : certs) {
					System.out.println("Cert Type : " + cert.getType());
					System.out.println("Cert Hash Code : " + cert.hashCode());
					System.out.println("Cert Public Key Algorithm : "
							+ cert.getPublicKey().getAlgorithm());
					System.out.println("Cert Public Key Format : "
							+ cert.getPublicKey().getFormat());
					System.out.println("\n");
				}

			} catch (SSLPeerUnverifiedException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private String print_content(HttpsURLConnection con) {
		String input = null;
		if (con != null) {

			try {
				System.out.println("****** Content of the URL ********");
				BufferedReader br = new BufferedReader(new InputStreamReader(
						con.getInputStream()));

				while ((input = br.readLine()) != null) {
					System.out.println(input);
				}
				br.close();

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return input;
	}

	public static String Encoding_Url(String url) {

		String jsonText = null;
		HttpParams params = new BasicHttpParams();
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, "utf-8");
		params.setBooleanParameter("http.protocol.expect-continue", false);

		HttpClient httpclient = new DefaultHttpClient(params);

		HttpGet httpget = new HttpGet(url);
		HttpResponse response;
		try {
			response = httpclient.execute(httpget);

			if (response.getStatusLine().getStatusCode() == 200) {
				// Connection was established. Get the content.

				HttpEntity entity = response.getEntity();
				// If the response does not enclose an entity, there is no need
				// to worry about connection release

				if (entity != null) {
					// A Simple JSON Response Read
					InputStream instream = entity.getContent();
					jsonText = convertStreamToString(instream);

					// Toast.makeText(getApplicationContext(),
					// "Response: "+jsonText, Toast.LENGTH_LONG).show();

				}

			}

		} catch (MalformedURLException e) {
			// Toast.makeText(getApplicationContext(),
			// "ERROR: Malformed URL - "+e.getMessage(),
			// Toast.LENGTH_LONG).show();
			e.printStackTrace();
		} catch (IOException e) {
			// Toast.makeText(getApplicationContext(),
			// "ERROR: IO Exception - "+e.getMessage(),
			// Toast.LENGTH_LONG).show();
			e.printStackTrace();
		}
		return jsonText;

	}

}
